package com.boot.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boot.common.Result;
import com.boot.entity.TUser;
import com.boot.service.IUserService;
import com.boot.utils.JWTUtil;
import com.boot.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * @author Chunsheng.Zhang
 * @date 2021/1/18 15:46
 * @description : TODO
 */
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;




    @PostMapping("/login")
    public Result login(TUser user, HttpServletResponse  response){

        redisUtil.set("0e661dd7536e4b83bfe105f1d2d6b7c2","0e661dd7536e4b83bfe105f1d2d6b7c2");

        if(StringUtils.isBlank(user.getAccount())||StringUtils.isBlank(user.getPassword())){
            return new Result().error("账号或密码不能为空");
        }

        //从数据库中查询用户
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",user.getAccount());
        wrapper.eq("password",user.getPassword());
        wrapper.eq("is_delete",1);
        wrapper.eq("status",0);
        TUser dataBaseUser = userService.getOne(wrapper);
        if(dataBaseUser == null){
            return new Result().error("该可用账户不存在，请核实后登陆");
        }

        //生成token，通过响应头返回
        String userStr = JSONObject.toJSONString(dataBaseUser);

        String token = jwtUtil.getToken(userStr) ;
        response.setHeader("token",token);

        log.info("token={}",token);

        return new Result().ok(dataBaseUser);
    }


    /**
     * @description: 查询所有用户
     * @author: ChunSheng.Zhang
     * @date: 2021/1/18 16:28

     * @return com.boot.common.Result
     **/
    @RequestMapping("/selAll")
    public Result selAll(){

        List<TUser> list = userService.list();
        return new Result().ok(list);
    }
}
